package com.demarc.pesquisas.infraestrutura.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Filtro abstrato com comportamento padrão (métodos init e destroy vazios) e
 * com método de redirecionamento.
 * 
 * @author ahdnc
 */
public abstract class AbstractFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// Comportamento padrão de não fazer nada.
	}

	protected void redirect(ServletRequest request, ServletResponse response,
			String page) throws IOException {
		try {
			HttpServletRequest req = (HttpServletRequest) request;
			HttpServletResponse res = (HttpServletResponse) response;

			StringBuilder redirectUrlBuilder = new StringBuilder();
			redirectUrlBuilder.append(req.getContextPath());
			redirectUrlBuilder.append(page);

			if (isAjax(req)) {
				res.getWriter()
						.print(xmlPartialRedirectToPage(redirectUrlBuilder
								.toString()));
				res.flushBuffer();
			} else {
				res.sendRedirect(redirectUrlBuilder.toString());
			}
		} catch (Exception e) { // NOPMD
			// nothing to do
		}
	}

	private boolean isAjax(HttpServletRequest request) {
		return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
	}

	private String xmlPartialRedirectToPage(String redirectUrl) {
		StringBuilder sb = new StringBuilder();
		sb.append("<?xml version='1.0' encoding='UTF-8'?>");
		sb.append("<partial-response><redirect url=\"").append(redirectUrl)
				.append("\"/></partial-response>");
		return sb.toString();
	}

	@Override
	public void destroy() {
		// Comportamento padrão de não fazer nada.
	}
}
